/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2025-03-18 19:58:05
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2025-03-19 21:00:18
 * @FilePath: /zhuang/ETEpollServer/Epoller.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <memory>
#include <iostream>
#include <string>
#include <functional>
#include "Log.hpp"
#include <poll.h>
#include <sys/epoll.h>
#include "Socket.hpp"
#include <cstring>
#include <errno.h>
#include<unordered_map>
using namespace std;
using namespace SocketModule;
using namespace LogModule;


namespace EpollModule
{
    class Epoller
    {
    public:
        Epoller()
        :_epfd(-1)
         {}

        void Init()
        {
            _epfd = ::epoll_create(256);
            if(_epfd < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_create error\n";
                exit(EPOLL_CREATE_ERR);
            }
            LOG(LogLevel::INFO) << "epoll_create success\n";
        } 

        int Wait(struct epoll_event revs[],int nums,int timeout)
        {
             int n = ::epoll_wait(_epfd,revs,nums,timeout); //设置为非阻塞
             if(n < 0)
             {
                LOG(LogLevel::WARNING)<<"epoll_wait error\n";
             }
             return n;
        }
         //节点注册进epoll
        void Ctrl(int sockfd,uint32_t events,int flag)
        {
              struct epoll_event ev;
              ev.events = events;
              ev.data.fd = sockfd;
              int n = ::epoll_ctl(_epfd,flag,sockfd,&ev);
              if(n < 0)
              {
                LOG(LogLevel::WARNING) << "epoll_ctrl error\n";
              }
        }
         //添加节点到红黑树中
        void Add(int sockfd,uint32_t events)
        {
              Ctrl(sockfd,events,EPOLL_CTL_ADD);
        }

        void Update(int sockfd,uint32_t events)
        {
             Ctrl(sockfd,events,EPOLL_CTL_MOD);
        }

        void Delete(int sockfd)
        {
           int n = ::epoll_ctl(sockfd,EPOLL_CTL_DEL,sockfd,nullptr);
           if(n < 0)
           {
             LOG(LogLevel::WARNING) << "epoll_ctl error";
           }
        }
        
        ~Epoller(){}

    private:
        int _epfd;
    };

}